var chessColor = '';
// let wsUri = "ws://114.55.248.167:8080/connection";
let wsUri = "ws://localhost:8080/connection";
let gameKey = '';
let websocket;
let passUserNum = 0;

/**
 * 连接服务器
 */
function connection() {
	if(!window.WebSocket) {
		alert("该浏览器不支持WebSocket无法进行游戏！");
	}
	websocket = new WebSocket(wsUri);
	websocket.onmessage = function(evt) {
		onMessage(evt)
	};
	websocket.onerror = function() {
		myAlert("error","与主机失去联系,请刷新页面重试！");
		gameError();
	};
	websocket.onclose = function() {
		myAlert("error","与主机失去联系,请刷新页面重试！");
		gameError();
	}
}

function onMessage(result) {
	let message = JSON.parse(result.data);
	if(message.gameState === "start") {
		gameKey = message.gameKey;
		let colorEnum = message.chessColor;
		chessColor = chessColorEnum[colorEnum];
		gameStart();
	} else if(message.gameState === "running") {
		passUserNum = 0;
		gameRunning(message);
	} else if(message.gameState === "pass") {
		let chessIndex = chessDownTurnEnum[message.chessColor];
		chessIndex += 1;
		passUserNum += 1;
		if(passUserNum === 4) {
			gameEnd();
		}
		if(chessIndex > 4) {
			chessIndex = 1;
		}
		if(chessColorEnum[chessIndex] === chessColor) {
			myTurn();
		} else {
			otherTurn();
		}
	}
}

function sendMessage(message) {
	message.gameKey = gameKey;
	message.chessColor = chessColor;
	websocket.send(JSON.stringify(message));
	passUserNum = 0;
}

function sendPassMsg() {
	let message = {
		"gameKey": gameKey,
		"chessColor": chessColor,
		"gameState": "pass"
	};
	websocket.send(JSON.stringify(message));
	passUserNum += 1;
	if(passUserNum === 4) {
		gameEnd();
	}
}